<template>
  <div class="app_wrap">
    <VScaleScreen width="1920" height="1080">
      <router-view></router-view>
    </VScaleScreen>
  </div>
</template>

<script>
import { defineComponent, nextTick } from "vue";
import "./App.scss";
export default defineComponent({
  name: "App",
});
</script>
<script setup>
import VScaleScreen from "v-scale-screen";
import { log } from "@/utils/log";
import { wsUrl } from "@/libs/baseUrl.js";
import { useWsDataStore } from "@/store";

const wsDataStore = useWsDataStore();

// nextTick
nextTick(() => {
  // socket
  let socket = null;
  // 是否连接
  let isConnected = false;
  // 重连次数
  let reconnectionCount = 0;
  // 连接地址
  const url = wsUrl;

  // 创建 WebSocket 连接
  const createWebSocket = () => {
    // 实例化 websocket
    socket = new WebSocket(url);

    // 监听 websocket 连接
    socket.onopen = () => {
      log.success("WebSocket connected");
      isConnected = true;
      // 连接之后重置重连次数
      reconnectionCount = 0;
    };

    // 监听 websocket 断开
    socket.onclose = () => {
      log.error("WebSocket disconnected");
      isConnected = false; // 判断是否达到最大重连次数

      if (reconnectionCount < 60) {
        reconnectionCount += 1; // 尝试重新连接

        setTimeout(() => {
          log.warning(`重新连接第${reconnectionCount}次!`);
          createWebSocket();
        }, 3000); // 3秒后尝试重新连接
      } else {
        log.error("放弃重连!!!");
      }
    };

    // 监听 websocket 消息
    socket.onmessage = (message) => {
      let data = JSON.parse(message.data);

      // 判断类型
      switch (data.type) {
        case 1:
          wsDataStore.updateRainfallRegulativeData(data.data);
          break;

        case 2:
          wsDataStore.updateWaterDevData(data.data);
          break;

        case 3:
          wsDataStore.updateAutoMedicateDevData(data.data);
          break;

        case 4:
          wsDataStore.updateSludgeTreatmentDevData(data.data);
          break;

        default:
          break;
      }
    };
  };

  createWebSocket();
});
</script>

<style lang="scss" scoped></style>
